package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.response.RollTimeCommandResp;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.vo.request.RollTimeDetectionReqVo;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.RollTimeCommand;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author cwj
 * @description
 * @date 2025/5/9 15:41
 **/
@Slf4j
@Service
public class RollTimeCommandService extends BaseService<RollTimeCommand> {

    @Resource
    private RedisClusterService redisClusterService;

    @Resource
    private KafkaService kafkaService;

    /**
     * @description 设置夜间睡眠检测（翻滚次数）功能
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/5/9 15:47
     **/
    public ResponseMap settingRollTimeDetection(RollTimeDetectionReqVo vo){
        //检查设备是否在线，不在线不能下发
        String onlineStatus = redisClusterService.hget(vo.getImei(), ConstCacheField.ONLINE_STATUS);
        if (!"1".equals(onlineStatus)) {
            return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
        }
        //保存或更新记录
        saveOrUpdateRollTimeCommand(vo);
        JSONObject kafkaJson = new JSONObject();
        kafkaJson.put("timeRegion", vo.getBeginTime()+"-"+vo.getEndTime());
        kafkaService.emitDeviceDemand(vo.getImei(), ConstKafka.ROLL_TIME_DETECTION, kafkaJson,vo.getOpenid());
        return ResponseMap.success();
    }

    /**
     * @description 保存或更新记录
     * @author cwj
     * @param [vo]
     * @return void
     * @date @time 2025/5/9 16:14
     **/
    private void saveOrUpdateRollTimeCommand(RollTimeDetectionReqVo vo) {
        Date date = new Date();
        //保存或更新设置是时间区间指令
        RollTimeCommand rollTimesCommand = this.findOne(new Query(Criteria.where("imei").is(vo.getImei())).limit(1));
        if(ObjectUtils.isEmpty(rollTimesCommand)) {
            //保存指令
            rollTimesCommand = new RollTimeCommand();
            rollTimesCommand.setBeginTime(vo.getBeginTime());
            rollTimesCommand.setEndTime(vo.getEndTime());
            rollTimesCommand.setImei(vo.getImei());
            rollTimesCommand.setCreateTime(date.getTime()/1000);
            rollTimesCommand.setUpdateTime(date.getTime()/1000);
            this.save(rollTimesCommand);
        } else {
            Update update = new Update();
            update.set("beginTime", vo.getBeginTime());
            update.set("endTime", vo.getEndTime());
            update.set("updateTime",date.getTime()/1000);
            this.updateById(new ObjectId(rollTimesCommand.getId()),update);
        }
    }


    /**
     * @description 查询睡眠检测信息
     * @author cwj
     * @param [imei]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/5/11 10:40
     **/
    public ResponseMap queryRollTimeCommand(String imei) {
        Query query = new Query();
        query.addCriteria(Criteria.where("imei").is(imei));
        RollTimeCommandResp rollTimeCommandResp = mongoTemplate.findOne(query,RollTimeCommandResp.class,"roll_time_command");
        ResponseMap res = ResponseMap.success();
        if(!ObjectUtils.isEmpty(rollTimeCommandResp)) {
            res.put("rollTimeCommandResp",rollTimeCommandResp);
        }
        return res;
    }

}
